function varargout = DrawSpt(varargin)
% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

% Edit the above text to modify the response to help DrawSpt

% Last Modified by GUIDE v2.5 29-Jun-2011 01:59:29

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DrawSpt_OpeningFcn, ...
                   'gui_OutputFcn',  @DrawSpt_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before DrawSpt is made visible.
function DrawSpt_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for DrawSpt
handles.output = hObject;
axes(handles.axes1); %#ok<MAXES>
axis off;
axes(handles.axes3); %#ok<MAXES>
axis off;
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes DrawSpt wait for user response (see UIRESUME)
 uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = DrawSpt_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2


% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
projectdir=uigetdir('','Select folder with project data');
set(handles.edit1,'String',projectdir);

listaAux=dir(fullfile(projectdir,'OUT','*.SPC')); 
m_listaPtos={listaAux.name};
listaAux=dir(fullfile(projectdir,'SWN','*.swn')); 
m_listaCasos={listaAux.name};
m_list=m_listaCasos;
m_spt=struct([]);

%%%
%obtencion de los casos de manera "simple".
for j=1:length(m_listaCasos)
    aux=regexp(m_listaCasos{j},'-H','split');
    aux=regexp(aux{2},'T','split');
    H=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'D','split');
    T=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'Lvl','split');
    D=str2double(regexprep(aux{1},'_','\.'));
    num=str2double(m_listaCasos{j}(1:2));
    if(num>1)
        kind='nested';
    else
        kind='';
    end
    m_list{j}=sprintf('H: %s | T: %s | D: %s | %s',H,T,dir2txt(D),kind);
    
    %espectros de oleaje en puntos de control
    fName=fullfile(projectdir,'OUT',m_listaPtos{j});
    m_spt(j).pcontrol=loadSWANPoints(fName);
    
    %%
    %cargamos los datos generales del caso
    archivo=fullfile(projectdir,'SWN',m_listaCasos{j});
    fh=fopen(archivo,'r');
    seguir=true; %variable de control
    while (~feof(fh)&&seguir)
        line=fgetl(fh);
        elem=regexp(line,'\s+', 'split');
        %condiciones contorno
        if ~isempty(findstr(elem{1},'BOUN'))&&~isempty(findstr(elem{2},'SIDE')) 
                Hs=str2double(elem{6});
                Tp=str2double(elem{7});
                m_spt(j).Hs=Hs;
                m_spt(j).Tp=Tp;
        end
    end
    
    
    if j==1
        numcas=length(m_spt(j).pcontrol{4});
        set(handles.popupmenu3,'String',linspace(1,numcas,numcas));
        
    end
end

set(handles.popupmenu1,'String',m_list);

handles.m_spt=m_spt;

guidata(hObject, handles);
updateDisplay(handles);
%%%%%




% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1

item=get(hObject,'Value');
numcas=length(handles.m_spt(item).pcontrol{4});
set(handles.popupmenu3,'String',linspace(1,numcas,numcas));
updateDisplay(handles);

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu3.
function popupmenu3_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu3
updateDisplay(handles);

% --- Executes during object creation, after setting all properties.
function popupmenu3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function updateDisplay(handles)

cla(handles.axes1,'reset');
cla(handles.axes3,'reset');

caso=get(handles.popupmenu1,'Value');
punto=get(handles.popupmenu3,'Value');

fr=handles.m_spt(caso).pcontrol{1}; %frecuencias
th=handles.m_spt(caso).pcontrol{2}; %direcciones
th=th';

%ojo, el SWAN da angulos negativos... porque empieza en ��264??
for v=1:length(th)
    if th(v)<0
        th(v)=th(v)+360;
    end
end
%codigo alternativo para generacion de los espectros

f=fr*ones(size(th)); %matriz con frecuencias para cada direccion
t=ones(size(fr))*th; %matriz con direcciones para cada frecuencia
spt=handles.m_spt(caso).pcontrol{4}{punto};
dtype='met-N';

dth=abs(t(1,2)-t(1,1));
df=diff(fr);
nfr=length(fr);
fspt=(sum(spt,2)*dth)';
[fmax,kmax]=max(fspt); [smax,ktmax]=max(spt(kmax,:));
thmax=t(kmax,ktmax);
Hsig=4*sqrt(0.5*(fspt(1:nfr-1)*df+fspt(2:nfr)*df));
Tp=handles.m_spt(caso).Tp;
%rosa de frec/direccion

roseDSpt(handles.axes1,f,t*pi/180,spt,Tp,Hsig,thmax,'solid',dtype);
%grafico de frec/energia
axes(handles.axes3);
plot(f,fspt,'b','LineWidth',2); grid on;
set(gca, ...
    'Box'               , 'off'     , ...
    'TickDir'           , 'out'     , ...
    'TickLength'        , [.02 .02] , ...
    'XMinorTick'        , 'on'      , ...
    'YMinorTick'        , 'on'      , ...
    'YGrid'             , 'on'      , ...
    'XColor'            , [.3 .3 .3], ...
    'YColor'            , [.3 .3 .3], ...
    'XMinorGrid'        , 'on'      , ...
    'GridLineStyle'     , '--'      , ...
    'MinorGridLineStyle', ':'       , ...
    'LineWidth'         , 1         , ...
    'FontSize'          , 8         );
xlabel('f (Hz)','fontsi',10);
ylabel('E (m^2s)','fontsi',10)

X=handles.m_spt(caso).pcontrol{3}(punto,1);
Y=handles.m_spt(caso).pcontrol{3}(punto,2);
set(handles.text9,'String',sprintf('X: %6.2f',X));
set(handles.text10,'String',sprintf('Y: %6.2f',Y));
